package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public ShoppingCart addShoppingCard(ShoppingCart shoppingCart) {
        ShoppingCart cartServiceOne=shoppingCartMapper.queryByUserId(shoppingCart);

        if(cartServiceOne!=null){
            Integer number = cartServiceOne.getNumber();
            cartServiceOne.setNumber(number+1);
            shoppingCartMapper.updateById(cartServiceOne);

        }else {
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.addShoppingCard(shoppingCart);
            cartServiceOne=shoppingCart;
        }
        return cartServiceOne;

    }

    @Override
    public List<ShoppingCart> list(Long userId) {
        List<ShoppingCart> shoppingCartList=shoppingCartMapper.list(userId);
        return shoppingCartList;
    }

    @Override
    public void clean(Long userId) {
        shoppingCartMapper.clean(userId);
    }

    @Override
    public ShoppingCart sub(ShoppingCart shoppingCart) {
        ShoppingCart cartServiceOne=shoppingCartMapper.queryByUserId(shoppingCart);

        Integer number = cartServiceOne.getNumber();
        if(number==1){
            shoppingCartMapper.delete(cartServiceOne.getUserId(),cartServiceOne.getDishId(),cartServiceOne.getSetmealId());
        }
        cartServiceOne.setNumber(number-1);
        shoppingCartMapper.updateByIdAndOr(cartServiceOne);
        return cartServiceOne;


//        if(cartServiceOne!=null){
//            Integer number = cartServiceOne.getNumber();
//            cartServiceOne.setNumber(number-1);
//            shoppingCartMapper.updateByDishIdOrsetmealId(cartServiceOne);
//        }
//            return cartServiceOne;

    }

//    @Override//此处有BUG
//    public void sub(Long dishId, Long setmealId) {
//        ShoppingCart shoppingCart=shoppingCartMapper.queryById(dishId,setmealId);
//        Integer number = shoppingCart.getNumber();
//        Integer newNumber=number-1;
//        shoppingCart.setNumber(newNumber);
//        shoppingCartMapper.updateByIdAndOr(shoppingCart.getId());
//    }




}
